import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Card,
  CardContent,
  CardMedia,
  CardActions,
  Button,
  IconButton,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Alert,
  CircularProgress,
  TextField,
  MenuItem,
  Pagination,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Avatar,
  Switch,
  FormControlLabel,
} from '@mui/material';
import {
  Edit,
  Delete,
  Visibility,
  Search,
  FilterList,
  Image,
  VideoFile,
  Person,
  Block,
  CheckCircle,
} from '@mui/icons-material';
import { useContent } from '../../hooks/useContent';
import { ContentEditor } from '../user/components';
import { Content, ContentListItem, ContentType, ContentQueryParams, UserRole } from '../../types';
import { userStorage } from '../../utils/api';

const AdminContentManagement: React.FC = () => {
  const { getAllContents, deleteContent, viewContent, loading } = useContent();
  const [contents, setContents] = useState<ContentListItem[]>([]);
  const [totalPages, setTotalPages] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedContent, setSelectedContent] = useState<Content | null>(null);
  const [editorOpen, setEditorOpen] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [contentToDelete, setContentToDelete] = useState<ContentListItem | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [viewMode, setViewMode] = useState<'grid' | 'table'>('table');

  // 搜索和筛选状态
  const [searchTitle, setSearchTitle] = useState('');
  const [contentTypeFilter, setContentTypeFilter] = useState<string>('all');
  const [sortBy, setSortBy] = useState<string>('created_at');
  const [userIdFilter, setUserIdFilter] = useState<string>('');

  // 检查管理员权限
  const currentUser = userStorage.get();
  const isAdmin = currentUser && (currentUser.role === UserRole.ADMIN || currentUser.role === UserRole.SUPERADMIN);

  // 加载内容列表
  const loadContents = async (page: number = 1) => {
    try {
      setError(null);
      const params: ContentQueryParams = {
        page,
        size: 20,
        ...(searchTitle && { title: searchTitle }),
        ...(contentTypeFilter !== 'all' && { contentType: contentTypeFilter }),
        ...(userIdFilter && { userId: parseInt(userIdFilter) }),
        orderBy: sortBy as any,
      };

      const response = await getAllContents(params);
      setContents(response.contents || []);
      setTotalPages(response.totalPages || 0);
      setCurrentPage(page);
    } catch (err) {
      setError('加载内容失败，请稍后重试');
      console.error('加载内容失败:', err);
    }
  };

  // 初始加载
  useEffect(() => {
    if (isAdmin) {
      loadContents();
    }
  }, [isAdmin]);

  // 搜索和筛选
  const handleSearch = () => {
    loadContents(1);
  };

  const handlePageChange = (event: React.ChangeEvent<unknown>, page: number) => {
    loadContents(page);
  };

  // 编辑内容
  const handleEditContent = async (content: ContentListItem) => {
    try {
      setError(null);
      // 调用API获取完整的内容详情
      const contentDetail = await viewContent(content.id);
      
      // 将ContentDetail转换为Content格式
      const fullContent: Content = {
        id: contentDetail.id,
        userId: contentDetail.userId,
        contentType: contentDetail.contentType,
        title: contentDetail.title,
        textContent: contentDetail.textContent,
        coverUrl: contentDetail.coverUrl,
        uploadStatus: content.uploadStatus, // 从列表项获取
        imageUrls: contentDetail.images.map(img => img.imageUrl),
        images: contentDetail.images, // 保存完整的图片信息
        videoUrls: contentDetail.videos.map(video => video.videoUrl),
        likeCount: contentDetail.likeCount,
        commentCount: contentDetail.commentCount,
        viewCount: contentDetail.viewCount,
        isPublished: contentDetail.isPublished,
        isLiked: contentDetail.isLiked,
        createdAt: contentDetail.createdAt,
        updatedAt: contentDetail.updatedAt,
      };
      
      setSelectedContent(fullContent);
      setEditorOpen(true);
    } catch (err) {
      setError('获取内容详情失败，请稍后重试');
      console.error('获取内容详情失败:', err);
    }
  };

  const handleEditorClose = () => {
    setEditorOpen(false);
    setSelectedContent(null);
  };

  const handleContentUpdate = (updatedContent: Content) => {
    setContents(prev => prev.map(content => 
      content.id === updatedContent.id ? {
        ...content,
        title: updatedContent.title,
        updatedAt: updatedContent.updatedAt,
      } : content
    ));
    setSuccess('内容更新成功');
  };

  // 删除内容
  const handleDeleteContent = (content: ContentListItem) => {
    setContentToDelete(content);
    setDeleteDialogOpen(true);
  };

  const confirmDelete = async () => {
    if (!contentToDelete) return;

    try {
      setError(null);
      await deleteContent(contentToDelete.id);
      setContents(prev => prev.filter(content => content.id !== contentToDelete.id));
      setSuccess('内容删除成功');
      setDeleteDialogOpen(false);
      setContentToDelete(null);
    } catch (err) {
      setError('删除失败，请稍后重试');
    }
  };

  // 格式化日期
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  // 获取上传状态颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'COMPLETED': return 'success';
      case 'UPLOADING': return 'warning';
      case 'FAILED': return 'error';
      default: return 'default';
    }
  };

  // 获取上传状态文本
  const getStatusText = (status: string) => {
    switch (status) {
      case 'COMPLETED': return '已完成';
      case 'UPLOADING': return '上传中';
      case 'UPDATING': return '更新中';
      case 'FAILED': return '失败';
      case 'PENDING': return '待处理';
      default: return status;
    }
  };

  if (!isAdmin) {
    return (
      <Box sx={{ maxWidth: 800, mx: 'auto', p: 3, textAlign: 'center' }}>
        <Alert severity="error">
          <Typography variant="h6">访问被拒绝</Typography>
          <Typography>您没有权限访问此页面，仅限管理员使用。</Typography>
        </Alert>
      </Box>
    );
  }

  return (
    <Box sx={{ maxWidth: 1400, mx: 'auto', p: 3 }}>
      {/* 页面标题 */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
        <Typography variant="h4" component="h1">
          内容管理
        </Typography>
        <Box sx={{ display: 'flex', gap: 2, alignItems: 'center' }}>
          <FormControlLabel
            control={
              <Switch
                checked={viewMode === 'table'}
                onChange={(e) => setViewMode(e.target.checked ? 'table' : 'grid')}
              />
            }
            label="表格视图"
          />
        </Box>
      </Box>

      {/* 搜索和筛选 */}
      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap', alignItems: 'center' }}>
            <TextField
              label="搜索标题"
              value={searchTitle}
              onChange={(e) => setSearchTitle(e.target.value)}
              size="small"
              sx={{ minWidth: 200 }}
              onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
            />
            
            <TextField
              label="用户ID"
              value={userIdFilter}
              onChange={(e) => setUserIdFilter(e.target.value)}
              size="small"
              type="number"
              sx={{ minWidth: 120 }}
            />
            
            <TextField
              select
              label="内容类型"
              value={contentTypeFilter}
              onChange={(e) => setContentTypeFilter(e.target.value)}
              size="small"
              sx={{ minWidth: 120 }}
            >
              <MenuItem value="all">全部</MenuItem>
              <MenuItem value="IMAGE">图文</MenuItem>
              <MenuItem value="VIDEO">视频</MenuItem>
            </TextField>

            <TextField
              select
              label="排序方式"
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value)}
              size="small"
              sx={{ minWidth: 120 }}
            >
              <MenuItem value="created_at">创建时间</MenuItem>
              <MenuItem value="like_count">点赞数</MenuItem>
            </TextField>

            <Button
              variant="contained"
              startIcon={<Search />}
              onClick={handleSearch}
              disabled={loading}
            >
              搜索
            </Button>
          </Box>
        </CardContent>
      </Card>

      {/* 错误和成功提示 */}
      {error && (
        <Alert severity="error" sx={{ mb: 2 }} onClose={() => setError(null)}>
          {error}
        </Alert>
      )}
      
      {success && (
        <Alert severity="success" sx={{ mb: 2 }} onClose={() => setSuccess(null)}>
          {success}
        </Alert>
      )}

      {/* 内容列表 */}
      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
          <CircularProgress />
        </Box>
      ) : contents.length === 0 ? (
        <Box sx={{ textAlign: 'center', py: 8 }}>
          <Typography variant="h6" color="text.secondary" gutterBottom>
            暂无内容
          </Typography>
          <Typography variant="body2" color="text.secondary">
            系统中还没有任何内容
          </Typography>
        </Box>
      ) : viewMode === 'table' ? (
        // 表格视图
        <TableContainer component={Paper}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>内容</TableCell>
                <TableCell>用户</TableCell>
                <TableCell>类型</TableCell>
                <TableCell>状态</TableCell>
                <TableCell>发布状态</TableCell>
                <TableCell>统计</TableCell>
                <TableCell>创建时间</TableCell>
                <TableCell>操作</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {contents.map((content) => (
                <TableRow key={content.id}>
                  <TableCell>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                      <Box
                        sx={{
                          width: 60,
                          height: 60,
                          borderRadius: 1,
                          overflow: 'hidden',
                          bgcolor: 'grey.100',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                        }}
                      >
                        {content.coverUrl ? (
                          <img
                            src={content.coverUrl}
                            alt={content.title}
                            style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                          />
                        ) : (
                          content.contentType === ContentType.IMAGE ? (
                            <Image color="disabled" />
                          ) : (
                            <VideoFile color="disabled" />
                          )
                        )}
                      </Box>
                      <Box>
                        <Typography variant="subtitle2" noWrap sx={{ maxWidth: 200 }}>
                          {content.title || '无标题'}
                        </Typography>
                        <Typography variant="caption" color="text.secondary">
                          ID: {content.id}
                        </Typography>
                      </Box>
                    </Box>
                  </TableCell>
                  <TableCell>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <Person fontSize="small" />
                      <Typography variant="body2">
                        ID: {content.userId}
                      </Typography>
                    </Box>
                  </TableCell>
                  <TableCell>
                    <Chip
                      label={content.contentType === ContentType.IMAGE ? '图文' : '视频'}
                      color={content.contentType === ContentType.IMAGE ? 'primary' : 'secondary'}
                      size="small"
                    />
                  </TableCell>
                  <TableCell>
                    <Chip
                      label={getStatusText(content.uploadStatus)}
                      color={getStatusColor(content.uploadStatus) as any}
                      size="small"
                    />
                  </TableCell>
                  <TableCell>
                    <Chip
                      label={content.isPublished ? '已发布' : '已删除'}
                      color={content.isPublished ? 'success' : 'default'}
                      size="small"
                    />
                  </TableCell>
                  <TableCell>
                    <Box sx={{ display: 'flex', gap: 1, flexDirection: 'column' }}>
                      <Typography variant="caption">
                        👍 {content.likeCount} 💬 {content.commentCount} 👀 {content.viewCount}
                      </Typography>
                    </Box>
                  </TableCell>
                  <TableCell>
                    <Typography variant="caption">
                      {formatDate(content.createdAt)}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <Box sx={{ display: 'flex', gap: 1 }}>
                      <IconButton
                        size="small"
                        onClick={() => handleEditContent(content)}
                        color="primary"
                      >
                        <Edit fontSize="small" />
                      </IconButton>
                      <IconButton
                        size="small"
                        onClick={() => handleDeleteContent(content)}
                        color="error"
                      >
                        <Delete fontSize="small" />
                      </IconButton>
                    </Box>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      ) : (
        // 网格视图
        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 3 }}>
          {contents.map((content) => (
            <Card key={content.id} sx={{ width: { xs: '100%', sm: 'calc(50% - 12px)', md: 'calc(33.33% - 16px)', lg: 'calc(25% - 18px)' } }}>
              <Box sx={{ position: 'relative', height: 200 }}>
                {content.coverUrl ? (
                  <CardMedia
                    component="img"
                    height="200"
                    image={content.coverUrl}
                    alt={content.title}
                    sx={{ objectFit: 'cover' }}
                  />
                ) : (
                  <Box
                    sx={{
                      height: '100%',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      bgcolor: 'grey.100',
                      color: 'grey.500',
                    }}
                  >
                    {content.contentType === ContentType.IMAGE ? (
                      <Image sx={{ fontSize: 48 }} />
                    ) : (
                      <VideoFile sx={{ fontSize: 48 }} />
                    )}
                  </Box>
                )}
                
                <Chip
                  label={content.contentType === ContentType.IMAGE ? '图文' : '视频'}
                  color={content.contentType === ContentType.IMAGE ? 'primary' : 'secondary'}
                  size="small"
                  sx={{ position: 'absolute', top: 8, left: 8 }}
                />
                
                <Chip
                  label={getStatusText(content.uploadStatus)}
                  color={getStatusColor(content.uploadStatus) as any}
                  size="small"
                  sx={{ position: 'absolute', top: 8, right: 8 }}
                />
              </Box>

              <CardContent>
                <Typography variant="h6" noWrap gutterBottom>
                  {content.title || '无标题'}
                </Typography>
                
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                  <Person fontSize="small" color="disabled" />
                  <Typography variant="caption" color="text.secondary">
                    用户ID: {content.userId}
                  </Typography>
                </Box>

                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
                  <Typography variant="caption" color="text.secondary">
                    {formatDate(content.createdAt)}
                  </Typography>
                  <Box sx={{ display: 'flex', gap: 1 }}>
                    <Chip label={`${content.likeCount} 赞`} size="small" variant="outlined" />
                    <Chip label={`${content.viewCount} 看`} size="small" variant="outlined" />
                  </Box>
                </Box>
              </CardContent>

              <CardActions sx={{ justifyContent: 'space-between', px: 2, pb: 2 }}>
                <Box>
                  <IconButton
                    size="small"
                    onClick={() => handleEditContent(content)}
                    color="primary"
                  >
                    <Edit />
                  </IconButton>
                  <IconButton
                    size="small"
                    onClick={() => handleDeleteContent(content)}
                    color="error"
                  >
                    <Delete />
                  </IconButton>
                </Box>
                <Chip
                  label={content.isPublished ? '已发布' : '已删除'}
                  color={content.isPublished ? 'success' : 'default'}
                  size="small"
                />
              </CardActions>
            </Card>
          ))}
        </Box>
      )}

      {/* 分页 */}
      {totalPages > 1 && (
        <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
          <Pagination
            count={totalPages}
            page={currentPage}
            onChange={handlePageChange}
            color="primary"
            size="large"
          />
        </Box>
      )}

      {/* 内容编辑器 */}
      <ContentEditor
        open={editorOpen}
        content={selectedContent}
        onClose={handleEditorClose}
        onUpdate={handleContentUpdate}
      />

      {/* 删除确认对话框 */}
      <Dialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
      >
        <DialogTitle>确认删除</DialogTitle>
        <DialogContent>
          <Typography>
            确定要删除内容 "{contentToDelete?.title}" 吗？此操作不可撤销。
          </Typography>
          <Alert severity="warning" sx={{ mt: 2 }}>
            删除内容将同时删除所有相关的点赞、评论和媒体文件。
          </Alert>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>
            取消
          </Button>
          <Button onClick={confirmDelete} color="error" autoFocus>
            确认删除
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default AdminContentManagement; 